package com.servlet;

import com.entity.BgUser;
import com.entity.Cart;
import com.entity.User;
import com.mail.SendEmail;
import com.service.FoodsService;
import com.service.UserService;
import com.service.impl.BgUserServletImpl;
import com.service.impl.FoodsServiceImpl;
import com.service.impl.UserServiceImpl;
import com.util.DateHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.mail.Email;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Pattern;

@WebServlet("/login.let")
public class UserServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        UserService userService = new UserServiceImpl();
        String type = req.getParameter("type");
        switch (type) {
            case "login":
                String username = req.getParameter("username");
                String password = req.getParameter("password");
                System.out.println(username);
                User user = userService.login(username, password);
                if (user == null) {
                    out.println("<script>alert('账号或密码错误');parent.window.location.href='home-1.jsp';</script>");
                } else {
                    session.setAttribute("user", user);
                    int userId=((User)session.getAttribute("user")).getId();
                    int cartNum=userService.getCartNum(userId);
                    session.setAttribute("cartNum",cartNum);
                    req.getRequestDispatcher("/foods.let?type=lovethree").forward(req, resp);
                }
                break;
            case "resLogin":
                String emailName = req.getParameter("email");
                String username2 = req.getParameter("emailName");
                String password2 = req.getParameter("password");
                User name = userService.selectName(username2);
                if (name == null) {
                    if (username2.equals(emailName)){
                        int registered = userService.registered(username2, password2);
                        if (registered > 0) {
                            out.print("yes");
                        } else {
                            out.print("no");
                        }
                    }else {
                        out.print("zz");
                    }

                } else {
                    out.print("zy");
                }
                break;
            case "exit":
                if (session.getAttribute("user") == null) {
                    out.println("<script>alert('请登录');parent.window.location.href='login.jsp';</script>");
                    return;
                }
                session.invalidate();
                out.println("<script>parent.window.location.href='/foods.let?type=lovethree';</script>");
                break;
            case "bglogin":
                String bgusername = req.getParameter("name");
                String bgpassword = req.getParameter("pwd");
                BgUserServletImpl bgUserServlet = new BgUserServletImpl();
                BgUser login = bgUserServlet.login(bgusername, bgpassword);
                if (login == null) {
                    out.println("<script>alert('账号或密码错误');parent.window.location.href='/bgFoodKa/login.html';</script>");
                } else {
                    session.setAttribute("bguser", login);
                    req.getRequestDispatcher(req.getContextPath() + "/bgFoodKa/index.jsp").forward(req, resp);
                }
                break;
            case "bgexit":
                if (session.getAttribute("bguser") == null) {
                    out.println("<script>alert('请登录');parent.window.location.href='/bgFoodKa/login.html';</script>");
                    return;
                }
                session.invalidate();
                out.println("<script>parent.window.location.href='/bgFoodKa/login.html';</script>");
                break;
            case "userList":
                List<User> users = userService.userList();
                req.setAttribute("user", users);
                req.getRequestDispatcher("").forward(req, resp);
                break;
            case "modify":
                try {
                    modify(req, resp, out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "modifyPwd":
                //1.验证用户是否的登录
                if (session.getAttribute("user") == null) {
                    out.println("<script>alert('请登录');parent.window.location.href='login.html';</script>");
                    return;
                }
                //修改密码
                //1.获取用户输入的新的密码
                String newPwd = req.getParameter("newpwd2");
                //2.获取用户的编号-session
                int id = ((User) session.getAttribute("user")).getId();
                //3.调用biz层方法
                int count = userService.modifyPwd(id, newPwd);
                //4.响应-参考exit
                if (count > 0) {
                    out.println("<script>alert('密码修改成功');parent.window.location.href='/login.jsp';</script>");
                } else {
                    out.println("<script>alert('密码修改失败');parent.window.location.href='/login.jsp';</script>");
                }
                break;
        }
    }
    /**
     * 修改用户信息的方法
     * @param req
     * @param resp
     * @param out
     */
    private void modify(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws Exception {

        //1.构建一个磁盘工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //1.1 设置大小
        factory.setSizeThreshold(1024*9);
        //1.2 临时仓库
        File file = new File("c:\\temp");
        if(!file.exists()){
            file.mkdir();//创建文件夹
        }
        factory.setRepository(file);

        //2.文件上传+表单数据
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //3.将请求解析成一个个FileItem(文件+表单元素)
        List<FileItem> fileItems = fileUpload.parseRequest(req);

        //4.遍历FileItem
        User user  =new User();
        for(FileItem  item: fileItems){
            if(item.isFormField()){
                //4.1 元素名称和用户填写的值  name: 文城
                String  name = item.getFieldName();
                String value = item.getString("utf-8");//防止乱码
                switch(name){
                    case "id":
                        user.setId(Integer.parseInt(value));
                        break;
                    case "pic":
                        user.setImage(value);
                        break;
                    case "name":
                        user.setName(value);
                        break;
                    case "address":
                        user.setAddress(value);
                        break;
                    case "phone":
                        user.setPhone(value);
                        break;
                }

            }else {
                //4.2 文件: 图片的文件名  文城.png,用户不选择图片时，fileName的数据为""
                String fileName = item.getName();
                //避免文件替换：当前的系统时间.png
                if(fileName.trim().length()>0) {
                    //4.2.1 获取后缀名 .png
                    String filterName = fileName.substring(fileName.lastIndexOf("."));
                    //4.2.2 修改文件名  20211117112512234.png
                    fileName = DateHelper.getImageName() + filterName;
                    //保存到哪里
                    //虚拟路径: Images/cover/1-1.png
                    //文件的读写:实际路径 D://xx  --> 虚拟路径: Images/cover对应的实际路径
                    String path = req.getServletContext().getRealPath("/assets/img/userImage");
                    //d:/xxx/xx/ 20211117112512234.png
                    String filePath = path + "/" + fileName;
                    //数据库表中的路径 ：Images/cover/101-1.png：相对项目的根目录的位置
                    String dbPath = "/assets/img/userImage/" + fileName;
                    user.setImage(dbPath);

                    //4.3 保存文件
                    item.write(new File(filePath));
                }
            }
        }

        //5.将信息保存到数据库
        int count = userService.modify(user);
        if(count>0){
            req.getSession().setAttribute("user",user);
            out.println("<script>alert('修改个人信息成功');top.location.replace('/PersonalCenter/main.jsp');</script>");
        }else{
            out.println("<script>alert('修改个人信息失败');location.href='/home-1.jsp';</script>");
        }
    }
}
